package indi.h.devmg.acquisition.wmi;

import org.jinterop.dcom.common.JIException;
import org.jinterop.dcom.common.JISystem;
import org.jinterop.dcom.core.*;
import org.jinterop.dcom.impls.JIObjectFactory;
import org.jinterop.dcom.impls.automation.IJIDispatch;
import org.jinterop.dcom.impls.automation.IJIEnumVariant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.UnknownHostException;
import java.util.logging.Level;

public class WmiService {

	private JIComServer m_ComStub = null;

	private IJIComObject m_ComObject = null;
	private IJIDispatch m_Dispatch = null;
	private String m_Address = null;
	private JISession m_Session = null;
	private IJIDispatch m_WbemServices = null;

	private static final String WMI_CLSID = "76A6415B-CB41-11d1-8B02-00600806D9B6";
	private static final String WMI_PROGID = "WbemScripting.SWbemLocator";

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	public WmiService(String address) {
		JISystem.setAutoRegisteration(true);
		JISystem.getLogger().setLevel(Level.WARNING);
		m_Address = address;
	}

	public void query(String strQuery) {

		System.out.println("query:" + strQuery);

		JIVariant results[] = new JIVariant[0];
		try {
			results = m_WbemServices.callMethodA("ExecQuery", new Object[] { new JIString(strQuery),
					JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM() });
			IJIDispatch wOSd = (IJIDispatch) JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());

			int count = wOSd.get("Count").getObjectAsInt();

			IJIComObject enumComObject = wOSd.get("_NewEnum").getObjectAsComObject();
			IJIEnumVariant enumVariant = (IJIEnumVariant) JIObjectFactory
					.narrowObject(enumComObject.queryInterface(IJIEnumVariant.IID));

			IJIDispatch wbemObject_dispatch = null;

			for (int c = 0; c < count; c++) {

				Object[] values = enumVariant.next(1);
				JIArray array = (JIArray) values[0];
				Object[] arrayObj = (Object[]) array.getArrayInstance();
				for (int j = 0; j < arrayObj.length; j++) {
					wbemObject_dispatch = (IJIDispatch) JIObjectFactory
							.narrowObject(((JIVariant) arrayObj[j]).getObjectAsComObject());
				}

				String str = (wbemObject_dispatch.callMethodA("GetObjectText_", new Object[] { 1 }))[0]
						.getObjectAsString2();
				System.out.println("(" + c + "):");
				System.out.println(str);
				System.out.println();
			}

		} catch (JIException e) {
			e.printStackTrace();
		}
	}

	public void connect(final String domain, final String username, final String password) {
		try {

			m_Session = JISession.createSession(domain, username, password);
			m_Session.useSessionSecurity(true);
			m_Session.setGlobalSocketTimeout(5000);

			m_ComStub = new JIComServer(JIProgId.valueOf(WMI_PROGID), m_Address, m_Session);

			IJIComObject unknown = m_ComStub.createInstance();
			m_ComObject = unknown.queryInterface(WMI_CLSID);

			m_Dispatch = (IJIDispatch) JIObjectFactory.narrowObject(m_ComObject.queryInterface(IJIDispatch.IID));
			JIVariant results[] = m_Dispatch.callMethodA("ConnectServer",
					new Object[] { new JIString(m_Address), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(),
							JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), JIVariant.OPTIONAL_PARAM(), 0,
							JIVariant.OPTIONAL_PARAM() });

			m_WbemServices = (IJIDispatch) JIObjectFactory.narrowObject((results[0]).getObjectAsComObject());

		} catch (JIException e) {
			e.printStackTrace();
			if (m_Session != null) {
				try {
					JISession.destroySession(m_Session);
				} catch (JIException e1) {
					logger.error(e.getMessage(), e);
				}
			}
		} catch (UnknownHostException e) {
			if (m_Session != null) {
				try {
					JISession.destroySession(m_Session);
				} catch (JIException e1) {
					logger.error(e.getMessage(), e);
				}
			}
		}
	}

	public void disconnect() {
		try {
			JISession.destroySession(m_Session);
		} catch (JIException e) {
			logger.error(e.getMessage(), e);
		}
	}

	public static void main(String[] args) {

		WmiService wmiService = new WmiService("192.168.0.165");

		// 域（一般为空字符），用户名，密码
		wmiService.connect("", "Administrator", "1995415@a");

		// //系统信息
		// wmiService.query("SELECT * FROM Win32_ComputerSystem");
		//
		// //CPU信息
		// wmiService.query("SELECT * FROM
		// Win32_PerfFormattedData_PerfOS_Processor WHERE Name != '_Total'");
		//
		// //内存信息
		// wmiService.query("SELECT * FROM
		// Win32_PerfFormattedData_PerfOS_Memory");
		// //磁盘信息
		// wmiService.query("SELECT * FROM
		// Win32_PerfRawData_PerfDisk_PhysicalDisk Where Name != '_Total'");
//从磁盘读取数据的平均时间（以秒为单位）
		//2206629917
		//2206629917
		wmiService.query("SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk");

		wmiService.disconnect();
	}
	// 获取系统信息
	// SELECT * FROM Win32_PerfFormattedData_PerfOS_System instance of Win32_PerfFormattedData_PerfOS_System
	// {
	// AlignmentFixupsPersec = 0;//系统固定故障率
	// ContextSwitchesPersec = 6077;//每秒上下文切换数，即进程间切换和线程间切换
	// ExceptionDispatchesPersec = 0;//系统发送异常的速率
	// FileControlBytesPersec = "2059";//除读写外的文件操作所控制的字节数，例如文件请求
	// FileControlOperationsPersec =
	// 39;//文件系统操作的组合速率，既不是读也不是写操作，例如文件系统控制请求和关于设备特性或状态的信息请求
	// FileDataOperationsPersec =
	// 1276;//每秒文件数据操作次数，即读次数加写次数(FileReadOperationsPersec+FileWriteOperationsPersec=FileDataOperationsPersec)
	// FileReadBytesPersec = "3288";//文件系统每秒读的速率
	// FileReadOperationsPersec = 614;//系统每秒总的读请求次数
	// FileWriteBytesPersec = "178811";//文件系统每秒写的速率
	// FileWriteOperationsPersec = 662;//系统每秒总的写请求次数
	// FloatingEmulationsPersec = 0;//每秒流动模拟
	// PercentRegistryQuotaInUse = 6;//系统当前正在使用的总注册配额的百分比
	// Processes = 74;//进程数
	// ProcessorQueueLength = 0;//处理器队列长度
	// SystemCallsPersec = 17311;//系统服务每秒调用次数
	// SystemUpTime = "1276";//现在启动了多久,按秒算
	// Threads = 1228;//电脑中线程数
	// };
	// 磁盘信息
	// SELECT * FROM Win32_PerfRawData_PerfDisk_PhysicalDisk Where Name
	// !='_Total'
	// instance of Win32_PerfRawData_PerfDisk_PhysicalDisk
	// {
	// AvgDiskBytesPerRead = "22183336960";
	// AvgDiskBytesPerRead_Base = 20523;
	// AvgDiskBytesPerTransfer = "56915725824";
	// AvgDiskBytesPerTransfer_Base = 54082;
	// AvgDiskBytesPerWrite = "34732388864";
	// AvgDiskBytesPerWrite_Base = 33559;
	// AvgDiskQueueLength = "5416456000";
	// AvgDiskReadQueueLength = "4108682000";
	// AvgDisksecPerRead = 1484602393;
	// AvgDisksecPerRead_Base = 20523;
	// AvgDisksecPerTransfer = 1957144295;
	// AvgDisksecPerTransfer_Base = 54082;
	// AvgDisksecPerWrite = 472541902;
	// AvgDisksecPerWrite_Base = 33559;
	// AvgDiskWriteQueueLength = "1307774000";
	// CurrentDiskQueueLength = 0;
	// DiskBytesPersec = "56915725824";
	// DiskReadBytesPersec = "22183336960";
	// DiskReadsPersec = 20523;
	// DiskTransfersPersec = 54082;
	// DiskWriteBytesPersec = "34732388864";
	// DiskWritesPersec = 33559;
	// Frequency_Object = "0";
	// Frequency_PerfTime = "3613330";
	// Frequency_Sys100NS = "10000000";
	// Name = "0 E: F: G:";//硬盘名称，一般以分割出的磁盘合并命名，总磁盘数据名字为_Total，所以一般不要_Total
	// PercentDiskReadTime = "4108682000";
	// PercentDiskReadTime_Base = "131486201555340430";
	// PercentDiskTime = "5416456000";
	// PercentDiskTime_Base = "131486201555340430";
	// PercentDiskWriteTime = "1307774000";
	// PercentDiskWriteTime_Base = "131486201555340430";
	// PercentIdleTime = "56490028000";
	// PercentIdleTime_Base = "131486201555340430";
	// SplitIOPerSec = 0;
	// Timestamp_Object = "0";
	// Timestamp_PerfTime = "21470265397";
	// Timestamp_Sys100NS = "131486201555340430";
	// };

	

}